const messageDao = require("../dao/messageDao");
const Blog = require("../dao/models/Blog");
const validate = require("validate.js");
const getRandomAvatar = require("../utils/getRandomAvatar");
const { ValidationError } = require("../utils/errors");

exports.getMessages = async (page, limit, blodId, token) => {
    return await messageDao.getMessages(page, limit, blodId, token);
}

exports.addMessage = async (info) => {
    const res = validate.validate(info, {
        nickname: {
            presence: {
                allowEmpty: false,
            },
            type: "string"
        },
        content: {
            presence: {
                allowEmpty: false,
            },
            type: "string"
        }
    });
    if (!res) {
        info.createDate = Date.now();
        if (!info.blogId) {
            info.blogId = null;
        }
        info.avatar = await getRandomAvatar();
        return await messageDao.addMessage(info);
    } else {
        throw new ValidationError("数据验证失败");
    }
}

exports.deleteMessage = async (id) => {
    await messageDao.deleteMessage(id);
    return true;
}
